const service = axios.create({
    baseURL: requestURL,
    timeout: 100000
});
service.interceptors.request.use(
    config => {
        config.headers.common['Authorization'] = sessionStorage.getItem('token');
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (Object.keys(response.headers).includes('authorization')) {
            var startStr = 'Bearer ';
            var token = response.headers.authorization;
            var myToken = token.startsWith(startStr) ? token.slice(startStr.length) : token;
            sessionStorage.setItem('token', myToken);
        }
        if (Object.keys(response.headers).includes('x-nxdo-realname')) {
            var realname = response.headers['x-nxdo-realname'];
            if (realname && realname !== null && realname !== '') {
                sessionStorage.setItem('realname', decodeURIComponent(realname));
            }
        }
        if (Object.keys(response.headers).includes('x-nxdo-mj')) {
            var realMj = response.headers['x-nxdo-mj'];
            if (realMj && realMj !== null && realMj !== '') {
                sessionStorage.setItem('realMj', realMj);
            }
        }
        window.addEventListener('storage', (event) => {
            if (event.key === 'isLogin' && event.newValue === '0') {
                if (sessionStorage.getItem('token')) {
                    ELEMENT.Message({
                        message: '当前登录用户已过期,请重新登录!',
                        type: 'warning',
                        duration: 0,
                        showClose: true,
                    });
                    sessionStorage.removeItem('token');
                    router.push('/login');
                }
            };
            if (event.key === 'isClose' && event.newValue === '0') {
                if (sessionStorage.getItem('token')) {
                    ELEMENT.Message({
                        message: '当前登录用户已过期,请重新登录!',
                        type: 'warning',
                        duration: 0,
                        showClose: true,
                    });
                    sessionStorage.removeItem('token');
                    router.push('/login');
                }
            };
        });
        if (res.length >= 0) {
            return res;
        } else if (res.code !== 20000) {
            //Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 });

            //// 50008: 非法Token; 50012: 其他客户端登录; 50014: Token过期; 50016 无权限;
            //if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
            //  // to re-login
            //  MessageBox.confirm('您已注销，可以取消以停留在此页面，或重新登录', '确认注销', {
            //    confirmButtonText: '重新登录',
            //    cancelButtonText: '取 消',
            //    type: 'warning'
            //  }).then(() => {
            //    store.dispatch('user/resetToken').then(() => {
            //      location.reload();
            //    });
            //  })
            //}
            //return Promise.reject(new Error(res.message || 'Error'));
            return res;
        } else {
            return res;
        }
    },
    error => {
        var statusCode = {
            401: '登录状态已过期，请重新登录',
            403: '当前登录用户没有业务系统权限'
        };
        if (location.href.includes('login')) {
            ELEMENT.Message({
                message: error.response.data.message || '登录失败，请检查网络后询问管理员',
                type: 'error',
                duration: 3000
            });
        } else {
            let retJson = '';
            // 请求流数据返回报错时,需要把返回的信息转换为JSON格式
            if (error.config.responseType === 'arraybuffer') {
                const decoder = new TextDecoder('utf-8');
                retJson = JSON.parse(decoder.decode(error.response.data));
            };
            ELEMENT.Message({
                message: statusCode[error.response.status] || error.response.data.message || retJson.message || '接口错误，请联系管理员',
                type: 'error',
                duration: 3000
            });
        }
        return Promise.reject(error);
    }
);

export default service;